<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\model\v1\AuditExam;
use app\api\model\v1\ChangeUnitLog;
use app\api\model\v1\EveryDayAnswerCensus;
use app\api\model\v1\OperateUserLog;
use app\api\model\v1\TopicUserDay;
use app\api\model\v1\TopicUserDaySync;
use app\api\model\v1\Unit;
use app\api\model\v1\UnitTotal;
use app\api\model\v1\Users;
use app\BaseController;
use Overtrue\Pinyin\Pinyin;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class Statistics extends BaseController
{

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/7 9:32
     * @param $unit_id 单位id
     * @param $mySelf 是否是自己表查询
     * @return array
     * 获取当前单位的下级菜单
     */
    public function getChildUnit($unit_id, $mySelf)
    {
        $children = $this->search->getChildrenIds(intval($unit_id), true);
        sort($children);
        if ($mySelf) {
            $where[] = ['id', 'in', $children];
        } else {
            $where[] = ['unit_id', 'in', $children];
        }
        return $where;
    }


    public function getParentUnt($unit_id)
    {
        $parent = $this->search->getParent(intval($unit_id));
        return $parent;
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/7 10:19
     * @param $unit_id
     * @return int
     * 统计网点总数
     */
    public function UnitCount($unit_id)
    {
        $res = UnitTotal::where(['unit_id' => $unit_id])->column('total');
        return reset($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/8 9:46
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 同步找到各个单位的下级统计总数入库
     */
//    public function syncUnitTotal()
//    {
//        $unit = Unit::select()->toArray();
//        foreach ($unit as $key => $value) {
//            $where = $this->getChildUnit($value['id'], true);
//            $user_where = $this->getChildUnit($value['id'], false);
//            $user_count = Users::field('id,username')->where($user_where)->where('is_admin', 0)->count();
//            $user_three_count = Users::field('id')->where($user_where)->where('wx_role_id', 3)->where('is_admin', 0)->count();
//            $user_four_count = Users::field('id')->where($user_where)->where('wx_role_id', 4)->where('is_admin', 0)->count();
//            $res = Unit::field('id')->where($where)->where('level', '=', Unit::LEVEL_THREE)->count();
//            $find = UnitTotal::where(['unit_id' => $value['id']])->find();
//            if (is_null($find)) {
//                UnitTotal::create([
//                    'unit_id' => $value['id'],
//                    'total' => $res,
//                    'persons_total' => $user_count,
//                    'answer_persons_total' => ($user_three_count + $user_four_count),
//                ]);
//            } else {
//                $find->save([
//                    'total' => $res,
//                    'persons_total' => $user_count,
//                    'answer_persons_total' => ($user_three_count + $user_four_count),
//                ]);
//            }
//
//        }
//        halt("成功");
//    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/15 13:48
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 同步日期
     */
//    public function a(){
//        $res = TopicUserDay::select()->toArray();
//        foreach ($res as $key=>$v){
//            $abc = strtotime($v['create_time']);
//            $date_of = date("Y-m-d",$abc);
//            TopicUserDay::update([
//                'id'=>$v['id'],
//                'date_of'=>$date_of
//            ]);
//        }
//
//        halt("wancheng");
//    }

//    public function a()
//    {
//        $date_of = date("Y-m-d");
//        $dateWhere[] = array('date_of', '=', '2022-06-09');
////        $res = TopicUserDay::where($dateWhere)->group('user_id')->select()->toArray();
//        $subQuery = Db::table('topic_user_day')
//            ->where($dateWhere)
//            ->where('is_sync',0)
//            ->order('error asc')
//            ->limit(1000000)
//            ->buildSql();
//        $res = Db::table($subQuery . ' a')
//            ->group('a.user_id')
//            ->order('a.id desc')
//            ->select()->toArray();
//        if(!empty($res)){
//            foreach ($res as $key => $v) {
//                $unit = Unit::withCount(['users'])->find($v['unit_id']);
//                $is_find = EveryDayAnswerCensus::where(['unit_id' => $v['unit_id'], 'date_of' => $v['date_of']])->find();
//                if (is_null($is_find)) {
//                    EveryDayAnswerCensus::create([
//                        'unit_id' => $v['unit_id'],
//                        'date_of' => $v['date_of'],
//                        'completed_number' => 1,
//                        'unit_number' => $unit['users_count'] ?? 0,
//                        'user_ids' => $v['user_id']
//                    ]);
//                } else {
//                    if ($is_find['unit_number'] != $unit['users_count']) {
//                        $is_find->save([
//                            'completed_number' => $is_find['completed_number'] + 1,
//                            'user_ids' => $is_find['user_ids'] . ',' . $v['user_id']
//                        ]);
//                    }
//                }
//                $is_f = TopicUserDaySync::where(['unit_id' => $v['unit_id'],'user_id'=>$v['user_id'],'date_of' => $v['date_of']])->find();
//                if (is_null($is_f)){
//                    // 把记录存放在同步表中！
//                    $res_sync = TopicUserDaySync::create([
//                        'user_id'=>$v['user_id'],
//                        'unit_id'=>$v['unit_id'],
//                        'date_of'=>$v['date_of'],
//                        'correct'=>$v['correct'],
//                        'error'=>$v['error'],
//                        'correct_rate'=>$v['correct_rate'],
//                        'duration'=>$v['duration'],
//                        'total_seconds'=>$v['total_seconds'],
//                        'score'=>$v['score'],
//                        'status'=>$v['status'],
//                        'is_admin'=>$v['is_admin'],
//                        'topic_user_day_id'=>$v['id'],
//                    ])->id;
//                    if ($res_sync){
//                        TopicUserDay::update([
//                            'id'=>$v['id'],
//                            'is_sync'=>1
//                        ]);
//                    }
//                }else{
//                    if (intval($v['score']) > intval($is_f['score'])){
//                        $is_f->save([
//                            'user_id'=>$v['user_id'],
//                            'unit_id'=>$v['unit_id'],
//                            'date_of'=>$v['date_of'],
//                            'correct'=>$v['correct'],
//                            'error'=>$v['error'],
//                            'correct_rate'=>$v['correct_rate'],
//                            'duration'=>$v['duration'],
//                            'total_seconds'=>$v['total_seconds'],
//                            'score'=>$v['score'],
//                            'status'=>$v['status'],
//                            'is_admin'=>$v['is_admin'],
//                            'topic_user_day_id'=>$v['id'],
//                        ]);
//                    }
//                }
//            }
//        }
//        halt("完成");
//    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/11 11:32
     * @param $unit_id
     * @return mixed
     * 已答题数--- 父级获取下级 -- 已答网点数
     * 一个网点多个人的情况下！ 如一个人没答题 $unit_num 就为0 否则为1  为0是没完成
     */
    public function getUnitAnswerNumber($unit_id, $dateWhere)
    {
        //子级单位
        $childUnit = $this->getChildUnit($unit_id, false);
        $res = EveryDayAnswerCensus::with(['unitTotal'])->where($dateWhere)->where($childUnit)->select()->toArray();
        $i = 0;
        foreach ($res as $key => $v) { //$v['unit_number']
            if ($v['completed_number'] === $v['unit_number']) {
                $i++;
//                $abc = Users::whereIn('id',$v['user_ids'])->select()->toArray();
//                foreach ($abc as $k=>$v1){
//                    if ($v1['is_admin'] === 0){
//
//                    }
//                }
            }
        }
        return $i;
    }


    public function mySelf($unit_id, $dateWhere, $user_id)
    {
        $where = $this->getChildUnit($unit_id, false);
        $res = TopicUserDaySync::where($where)->where(['is_admin' => 0])->where($dateWhere)->where('user_id', $user_id)->group('unit_id')->count();

        return $res;
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/16 10:52
     * @param $unit_id
     * @param $dateWhere
     * @return mixed
     * 已答题数--- 个人
     */
    public function getSelfUnitAnswerNumber($unit_id, $dateWhere)
    {
        $where = $this->getChildUnit($unit_id, false);
        $res = TopicUserDay::where($where)->where(['is_admin' => 0])->where($dateWhere)->group('unit_id')->count();
        return $res;
    }

    /** **********************基层网点************************* */
    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/7 9:51
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 日情况统计表
     */
    public function dayTj()
    {
        if ($this->request->has('unit_id') && !empty($this->request->param('unit_id'))) {
            $where = $this->getChildUnit($this->request->param('unit_id'), false);
        } else {
            $where = [];
        }
        $res = $this->dayJs($where);
        return $this->response($res);

    }


    /** ****************************************县、区答题情况统计报表********************************************* **/

    //县区日统计
    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/7 9:59
     *
     * 网点总数
     * 答题网点数
     * 网点答题率
     * 正确率
     * 错误率
     */

    public function countyAreaDayTj()
    {
        if ($this->request->has('unit_id') && !empty($this->request->param('unit_id'))) {
            $where = $this->getChildUnit($this->request->param('unit_id'), false);
            $unit_count = $this->UnitCount($this->request->param('unit_id'));
        } else {
            $where = [];
            $unit_count = 0;
        }
        //今日已答题 -- 网点数
        $day_count = TopicUserDay::where($where)->whereDay('create_time')->count();
        //网点答题率
        $unit_rate = round(($day_count / $unit_count) * 100, 2);
        halt($unit_rate);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/7 11:27
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 首页统计
     */
    public function homeTj()
    {
//        $date_of = '2022-06-02';
//        $user_id = 2466;
//        $unit_id = 230;
        $dateWhere[] = array('date_of', '=', $this->request->param('date_of', date("Y-m-d")));
        $user_id = $this->request->param('user_id', 0);
        $unit_id = $this->request->param('unit_id', 0);
        $level = $this->request->param('level', 0); //层级
        if (intval($unit_id) === 0) {
            $unit_id = 230; //省级id
        }
//        $unit = Unit::field('id,level')->find($unit_id);
//        if (is_null($unit)) {
//            return $this->response(404, '单位不存在');
//        }
        //父级单位
        $parentUnit = $this->getParentUnt($unit_id);
        //子级单位
        $childUnit = $this->getChildUnit($unit_id, false);
        //获取子级网点总数
        $unit_child_count = $this->UnitCount($unit_id);
        //1.2查找自己的层级关系
        $childUnitTitle = $this->tjTitleByLevel($level);
        if ($level === Unit::LEVEL_THREE) {
            //获取已答题的网点数 -- 个人
            $childUnitAnswerNumber = $this->mySelf($unit_id, $dateWhere, $user_id);
        } else {
            //获取已答题的网点数 -- 父级
            $childUnitAnswerNumber = $this->getUnitAnswerNumber($unit_id, $dateWhere);
        }
        if (!empty($parentUnit)) {
            //1.存在父级的时候
            //1.1 获取父级的单位id
            $parent_res = $this->getChildUnit($parentUnit[0]['id'], false);
            //获取父级网点总数
            $unit_parent_count = $this->UnitCount($parentUnit[0]['id']);
            //获取父级已答题的网点数
            $parentUnitAnswerNumber = $this->getUnitAnswerNumber($parentUnit[0]['id'], $dateWhere);
            //每日统计封装方法
            $parentResult = $this->dayJs($parent_res, $dateWhere);
            //获取标题
            $parentUnitTitle = $this->tjTitleByLevel($parentUnit[0]['level']);
            $is_parent = true;
        } else { //不存在父级的时候
            $parentResult = [];
            $is_parent = false;
            $parentUnitTitle = [
                'title' => '',
                'table_title' => ''
            ];
            $unit_parent_count = 0;
            $parentUnitAnswerNumber = 0;
        }
        if ($unit_child_count > 0) {
            $mySelfUnitAnswerNumberRate = round(($childUnitAnswerNumber / $unit_child_count) * 100, 2);
        } else {
            $mySelfUnitAnswerNumberRate = 0;
        }
        if ($unit_parent_count > 0) {
            $myParentUnitAnswerNumberRate = round(($parentUnitAnswerNumber / $unit_parent_count) * 100, 2);
        } else {
            $myParentUnitAnswerNumberRate = 0;
        }

        //1.1 查找自己的数据
        $childResult = $this->dayJs($childUnit, $dateWhere);
        $new_arr = [
            'result' => [
                'mySelf' => $childResult,
                'mySelfTitle' => $childUnitTitle['title'],
                'mySelfTableTitle' => $childUnitTitle['table_title'],
                'mySelfUnitCount' => $unit_child_count,
                'mySelfUnitAnswerNumber' => $childUnitAnswerNumber,
                'myParentUnitAnswerNumber' => $parentUnitAnswerNumber,
                'mySelfUnitAnswerNumberRate' => $mySelfUnitAnswerNumberRate, //自己的答题率
                'myParentUnitAnswerNumberRate' => $myParentUnitAnswerNumberRate,//父级的答题率
                'myParent' => $parentResult,
                'myParentTitle' => $parentUnitTitle['title'],
                'myParentTableTitle' => $parentUnitTitle['table_title'],
                'myParentUnitCount' => $unit_parent_count,
            ],
//            'sixteenCity' => $city,
            'is_parent' => $is_parent,
//            'is_parent_null' => $is_parent_null,
        ];
        return $this->response($new_arr);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/9 10:37
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取所有下级的统计数据 -- 16个地址
     */
    public function getDsTj()
    {
        $dateWhere[] = array('date_of', '=', $this->request->param('date_of', date("Y-m-d")));
        $unit_id = $this->request->param('unit_id', 0);
        $res = $this->tj($unit_id, 6, $dateWhere);
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/9 8:59
     * @param $unit_id
     * @param $type
     * @param $dateWhere
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 统计
     */
    public function tj($unit_id, $type, $dateWhere)
    {

        $res = Unit::with(['unitTotal'])->field('id,unit_title,level')->where('pid', $unit_id)->limit($type)->select()->each(function ($item, $key) use ($dateWhere) {
            $childUnit = $this->getChildUnit($item['id'], false);

            //已经答题人数
            $already_answer_persons = EveryDayAnswerCensus::where($childUnit)->where($dateWhere)->group('unit_id')->sum('completed_number');
//            //获取子级网点总数
//            $unit_count = $this->UnitCount($item['id']);
            //获取已答题的网点数
            $childUnitAnswerNumber = $this->getUnitAnswerNumber($item['id'], $dateWhere);

            $result = $this->dayJs($childUnit, $dateWhere);
            $unitAnswerNumberRate = 0;
            if (!empty($item['unitTotal'])) {
                if ($item['unitTotal']['total'] > 0) {
                    $unitAnswerNumberRate = round(($childUnitAnswerNumber / $item['unitTotal']['total']) * 100, 2);
                }
            }
            $item['already_answer_persons'] = intval($already_answer_persons) ?? 0;
            $item['unitAnswerNumberRate'] = $unitAnswerNumberRate;
            $item['result'] = $result;
            $item['result_sort'] = $result['correct_rate'];
            return $item;
        })->toArray();
        return $res;
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/9 17:29
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 单位排名
     */
    public function unitPm()
    {
        $date_of_arr = explode('/', $this->request->param('date_of'));
        $dateWhere = [];
        if (count($date_of_arr) > 1) {
            $dateWhere[] = array('date_of', 'between', [$date_of_arr[0], $date_of_arr[1]]);
        } else {
            $dateWhere[] = array('date_of', '=', $date_of_arr[0]);
        }
        $unit_id = $this->request->param('unit_id', 0);
        $unit = Unit::find($unit_id);
        if (is_null($unit)) {
            return $this->response(404, '暂无此单位');
        }
        $tableTitle = $this->tjTitleByLevel($unit->level);
        $headers[] = array('label' => $tableTitle['table_title'], 'key' => 'unit_title');
        if ($unit['level'] === Unit::LEVEL_TWO) {
            $headers[] = array('label' => '答题人', 'key' => 'username');
        } else {
            $headers[] = array('label' => '网点数', 'key' => 'unit_count');
        }
        $headers[] = array('label' => '完成率', 'key' => 'unitAnswerNumberRate');
        $headers[] = array('label' => '准确率', 'key' => 'correct_rate');
        $headers[] = array('label' => '需答题人数', 'key' => 'answer_persons_total');
        $headers[] = array('label' => '已答题人数', 'key' => 'already_answer_persons');
        $contents = [];

        $res = $this->tj($unit_id, 126, $dateWhere);
        foreach ($res as $key => $v) {
            $contents[$key]['id'] = $v['id'];
            $contents[$key]['level'] = $v['level'];
            $contents[$key]['unit_title'] = $v['unit_title'] ?? '----';
            $contents[$key]['username'] = $v['result']['title'] ?? '----';
            $contents[$key]['unit_count'] = $v['unitTotal']['total'] ?? 0;
            if ($v['unitAnswerNumberRate'] >= 100) {
                $unitAnswerNumberRate = 100;
            } else {
                $unitAnswerNumberRate = $v['unitAnswerNumberRate'] ?? '0';
            }
            $contents[$key]['unitAnswerNumberRate'] = $unitAnswerNumberRate;
            $contents[$key]['correct_rate'] = $v['result']['correct_rate'] ?? '0';
            $contents[$key]['answer_persons_total'] = $v['unitTotal']['answer_persons_total'] ?? 0; //需答题人数
            $contents[$key]['already_answer_persons'] = $v['already_answer_persons'] ?? 0; //已经答题人数
        }
        $new_data = [
            'headers' => $headers,
            'contents' => $contents,
            'tableTitle' => $tableTitle
        ];
//        if (empty($res)) {
//            $childUnit = $this->getChildUnit($unit_id, true);
//            $res = Unit::field('id,unit_title')->where($childUnit)->select()->each(function ($item, $key) {
//                $childUnit = $this->getChildUnit($item['id'], false);
//                $result = $this->dayJs($childUnit);
//
//                $item['data'] = $result;
//                $item['result_sort'] = $result['correct_rate'];
//                return $item;
//            })->toArray();
//        }
        return $this->response($new_data);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/9 11:42
     * @param $level
     * @return array
     * 获取标题
     */
    public function tjTitleByLevel($level)
    {
        switch ($level) {
            case 0:
                $table_title = "分公司";
                break;
            case 1:
                $table_title = "区县名称";
                break;
            case 2:
            case 3:
            default:
                $table_title = "网点名称";
                break;
        }
        $data = [
            'title' => Unit::$is_level[$level],
            'table_title' => $table_title
        ];
        return $data;
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/7 10:59
     * @param $where
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 每日统计封装方法
     */
    public function dayJs($where, $date_of_arr)
    {
        $res = TopicUserDaySync::field('(id) as id,(user_id) as user_id,(unit_id) as unit_id,(date_of) as date_of,(correct) as correct,(error) as error')->with(['user'])->where($where)->where($date_of_arr)->where(['is_admin' => 0])->group('user_id')->select()->toArray();

        $new_arr = [];
        $count = 0;
        $correct_count = 0;
        $title = "";
        foreach ($res as $key => $v) {
            $count += 10;
            $correct_count += $v['correct'];
            $nihao = $v['user']['username'] ?? $v['user_id'];
            $title .= $nihao . ',';
        }
        $new_arr['count'] = $count;
        $new_arr['correct_count'] = $correct_count;
        $new_arr['title'] = rtrim($title,',') ?? '';
        if ($count > 0) {
            $new_arr['correct_rate'] = round(($correct_count / $count) * 100, 2);
        } else {
            $new_arr['correct_rate'] = 0;
        }
        return $new_arr;
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/9 14:31
     * @return \think\response\Json
     * 分值排行
     */
    public function randMonth()
    {
        $learn_id = $this->request->param('learn_id', 0);
        $redis_key = 'monthly_test:'.$learn_id;
        $redis_arr = $this->redis->ZREVRANGE($redis_key, 0, -1, ['withscores' => true]);
        $new_arr = [];
        foreach ($redis_arr as $key => $v) {
            $new_arr[] = json_decode($key, true);
            foreach ($new_arr as $key1=>$value){
                $user = Users::findOrEmpty($value['id']);
                if (!$user->isEmpty()){
                    $new_arr[$key1]['head_img'] = $user->head_img;
                }
            }
        }
        if (empty($new_arr)) {
            return $this->response(404, '当前数据为空');
        }
        return $this->response($new_arr);
    }


    public function getUnitPerson()
    {

        $unit_id = $this->request->param('unit_id');
        $date_of_arr = explode('/', $this->request->param('date_of'));
        $dateWhere = [];
        if (count($date_of_arr) > 1) {
            $dateWhere[] = array('date_of', 'between', [$date_of_arr[0], $date_of_arr[1]]);
        } else {
            $dateWhere[] = array('date_of', '=', $date_of_arr[0]);
        }
        //获取子级网点总数
        $unit_count = $this->UnitCount($unit_id);

        //获取已答题的网点数
        //获取已答题的网点数 -- 个人
        $childUnitAnswerNumber = $this->getUnitAnswerNumber($unit_id, $dateWhere);
        $res = TopicUserDay::with(['unit', 'user'])->withCount(['topic' => function ($qqq) use ($dateWhere) {
            $qqq->where($dateWhere);
            return $qqq;
        }])
            ->withCount(['topic' => function ($query2, &$alias2) use ($dateWhere) {
                $query2->where(['is_error' => 1])->where($dateWhere);
                $alias2 = 'error_count';
                return $query2;
            }])
            ->withCount(['topic' => function ($query3, &$alias3) use ($dateWhere) {
                $query3->where(['is_error' => 0])->where($dateWhere);
                $alias3 = 'correct_count';
                return $query3;
            }])->where(['unit_id' => $unit_id])->where($dateWhere)->order('correct_count desc')->select()->each(function ($item, $key) use ($unit_count, $childUnitAnswerNumber) {
                if ($unit_count > 0) {
                    $unitAnswerNumberRate = round(($childUnitAnswerNumber / $unit_count) * 100, 2);

                } else {
                    $unitAnswerNumberRate = 0;
                }
                $item['unit_count'] = $unit_count;
                $item['unitAnswerNumberRate'] = $unitAnswerNumberRate;
                if ($item['topic_count'] > 0) {
                    $item['rate'] = round(($item['correct_count'] / $item['topic_count']) * 100, 2);
                } else {
                    $item['rate'] = 0;
                }
                return $item;
            })->toArray();
        if (empty($res)){
            return $this->response(404,'暂未找到该数据');
        }
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/13 16:12
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取单位下的所有用户
     */
    public function getUnitAdmins()
    {
        $unit_id = $this->request->param('unit_id', 0);
        $childUnit = $this->getChildUnit($unit_id, false);
        $res = Users::field('id,username,mobile,unit_id')->with(['unit'])->where($childUnit)->select();
        return $this->response($res);
    }





    public function echartsUnit(){
//        $data = $this->request->param();

        $dateWhere[] = array('date_of', '=', date("Y-m-d"));
        $res = TopicUserDaySync::field('count(*) as value,correct as name')->where($dateWhere)->group('correct')->select();
        return $this->response($res);
    }



    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/13 16:57
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取单位
     */
    public function getUnitListAll()
    {
        $unit_id = $this->request->param('unit_id', 0);
        $childUnit = $this->getChildUnit($unit_id, true);
        $res = Unit::field('id,unit_title')->where($childUnit)->where(['level' => Unit::LEVEL_THREE])->select();
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/5/13 17:26
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 更改网点
     */
    public function changeUnit()
    {
        $data = $this->request->param();
        $user = Users::with(['unit'])->find($data['user_id']);
        if (is_null($user)) {
            return $this->response(404, '当前人不存在');
        }
        $data['old_unit_id'] = $user['unit_id'];
        $data['old_unit_title'] = $user['unit']['unit_title'];
        $data['new_unit_id'] = $data['unit_id'];
        $data['new_unit_title'] = $data['unit_title'];
        $data['exercise_user_id'] = $this->request->wx_id;
        $data['unit_id'] = $this->request->wx_unit_id;
        ChangeUnitLog::create($data);
        return $this->response();
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 入网
     */
    public function enterUnit()
    {
        $data = $this->request->param();
        $data['new_unit_id'] = $data['unit_id'];
        $data['new_unit_title'] = $data['unit_title'];
        $data['exercise_user_id'] = $this->request->wx_id;
        $data['unit_id'] = $this->request->wx_unit_id;
        $data['type'] = ChangeUnitLog::IS_TYPE_ONE;
        ChangeUnitLog::create($data);
        return $this->response();
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 当前自己申请的记录
     */
    public function getChangeUnitLog()
    {
        $res = ChangeUnitLog::where(['exercise_user_id' => $this->request->wx_id])->order('create_time desc')->select();
        return $this->response($res);
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * h获取下级菜单的待审核记录
     */
    public function getIsAuditUnit()
    {
        $unit_id = $this->request->param('unit_id', 0);
        $unit_arr_ids = Unit::where(['pid' => $unit_id])->column('id');

        $res = ChangeUnitLog::with(['user'])->whereIn('unit_id', $unit_arr_ids)->where(['is_audit' => ChangeUnitLog::IS_AUDIT_ZERO])->order('create_time desc')->select()->toArray();
        return $this->response($res);

    }


    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 审核按钮 --- 转网记录
     */
    public function saveIsAudit()
    {
        $type = $this->request->param('type', 0);
        $change_id = $this->request->param('id');
        $is_find = ChangeUnitLog::find($change_id);
        if (is_null($is_find)) {
            return $this->response(404, '未找到当前记录');
        }
        if ($is_find['is_audit'] !== ChangeUnitLog::IS_AUDIT_ZERO) {
            return $this->response(404, '当前记录已经审核，请勿重复提交');
        }
        if ($type == ChangeUnitLog::IS_AUDIT_ONE) {
            //进行业务逻辑的操作
            if ($is_find['type'] == ChangeUnitLog::IS_TYPE_ZERO) {
                //转网
                $user = Users::find($is_find['user_id']);
                if (is_null($user)) {
                    return $this->response(404, '用户不存在');
                }
                $user->save(['unit_id' => $is_find['new_unit_id']]);
            } else if ($is_find['type'] = ChangeUnitLog::IS_TYPE_ONE) {
                //入网
                $user = Users::where('mobile', $is_find['mobile'])->find();
                if (!is_null($user)) {
                    return $this->response(404, '该手机号已经存在');
                }
                Users::create([
                    'username' => $is_find['username'] ?? '',
                    'nickname' => $is_find['username'] ?? '',
                    'mobile' => $is_find['mobile'] ?? '',

                    'password' => password_hash('111111', PASSWORD_DEFAULT),
                    'unit_id' => $is_find['new_unit_id'],
                    'industry_id' => 1,
                    'create_id' => $this->request->wx_id,
                ]);
            }
        }
        //更新状态后
        $is_find->save(['is_audit' => $type]);
        return $this->response();

    }


    /**
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 检测是否更改了unit——id
     */
    public function checkIsChangeUnitId()
    {
        $user_id = $this->request->param('user_id');
        $unit_id = $this->request->param('unit_id');
        $user = Users::find($user_id);

        if (!is_null($user) && intval($user['unit_id']) === intval($unit_id)) {
            $is_flag = true;
        } else {
            $is_flag = false;
        }
        return $this->response(['flag' => $is_flag]);
    }

    public function test()
    {
        $user = Users::select()->toArray();
        foreach ($user as $key => $value) {
            $unit = Unit::find($value['unit_id']);
            if (!is_null($unit)) {
                if ($unit['level'] !== Unit::LEVEL_THREE) {

                    Users::update([
                        'id' => $value['id'],
                        'is_admin' => 1,
                    ]);
                }
            }

        }
        halt(1111111);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/16 11:24
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 查看网点人员
     */
    public function getUnitUser()
    {
        $unit = Unit::find($this->request->param('unit_id', 0));
        if (is_null($unit)) {
            return $this->response(404, '暂无此单位');
        }
        $tableTitle = $this->tjTitleByLevel($unit->level);
        $headers[] = array('label' => $tableTitle['table_title'], 'key' => 'unit_title');
        $headers[] = array('label' => '网点数', 'key' => 'unit_count');
        $headers[] = array('label' => '答题人员数', 'key' => 'answer_persons_total');
        $contents = [];
        $res = Unit::with(['unitTotal'])->field('id,unit_title,level')->where('pid', $this->request->param('unit_id', 0))->select()->toArray();
        foreach ($res as $key => $v) {
            $contents[$key]['id'] = $v['id'];
            $contents[$key]['level'] = $v['level'];
            $contents[$key]['unit_title'] = $v['unit_title'] ?? '----';
            $contents[$key]['unit_count'] = $v['unitTotal']['total'] ?? 0;
            $contents[$key]['answer_persons_total'] = $v['unitTotal']['answer_persons_total'] ?? 0; //需答题人数
        }
        $new_data = [
            'headers' => $headers,
            'contents' => $contents,
            'tableTitle' => $tableTitle
        ];
        return $this->response($new_data);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/16 14:08
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取网点人员数
     */
    public function getCheckUnitPerson()
    {
        $unit_id = $this->request->param('unit_id', 0);
        $user = Users::with(['unit'])->where('unit_id', $unit_id)->whereIn('wx_role_id', [3, 4])->select()->each(function ($item, $key) {
            $unit_parent_arr = $this->search->getParents($item['unit_id']);
            $unit_parent_str = "";
            foreach ($unit_parent_arr as $key => $value) {
                if ($value['pid'] !== 0) {
                    $unit_parent_str .= $value['unit_title'] . '-';
                }

            }
            $item['unit_parent'] = rtrim($unit_parent_str, '-');
            return $item;
        })->toArray();
        return $this->response($user);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/16 15:08
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 移除用户
     */
    public function removeUser()
    {
        $data = $this->request->param();
        //1.查询用户
        $user = Users::find($data['user_id']);
        if (is_null($user)) {
            return $this->response(404, '未找到该用户');
        }
        //2.查询每日答题的表[topic_user_day]  条件为网点id 及用户id
        $topic_user_day_res = TopicUserDay::where(['unit_id' => $data['unit_id']])->where('user_id', $data['user_id'])->select();
        //判断是否为空
        if (!$topic_user_day_res->isEmpty()) {
            // 2.1 查询后进行删除
            $topic_user_day_res->delete();
        }
        //3.查询每日答题同步表[topic_user_day_sync] 条件为网点id 及用户id
        $topic_user_day_sync_res = TopicUserDaySync::where(['unit_id' => $data['unit_id']])->where('user_id', $data['user_id'])->select();
        //判断是否为空
        if (!$topic_user_day_sync_res->isEmpty()) {
            //3.1 查询后进行删除
            $topic_user_day_sync_res->delete();
        }
        //5.删除用户
        $user->delete();
        //6.总人数
        $persons_total = Users::where('unit_id', $data['unit_id'])->count();
        //7.答题人数 [3,4] 均为可答题人员
        $user_total = Users::where('unit_id', $data['unit_id'])->whereIn('wx_role_id', [3, 4])->count();
        //8.查询单位总数表[unit_total] 条件为网点id
        $unit_total_res = UnitTotal::where(['unit_id' => $data['unit_id']])->find();
        if (!is_null($unit_total_res)) {
            $unit_total_res->save([
                'persons_total' => $persons_total,
                'answer_persons_total' => $user_total,
            ]);
        }
        //9.每日答题统计答题网点是否完成答题表[every_day_answer_census]  whereFindInSet 查询当前user_ids中是否包含该用户 条件为网点id 及用户id
        $every_day_answer_census_res = EveryDayAnswerCensus::where(['unit_id' => $data['unit_id']])->whereFindInSet('user_ids', $data['user_id'])->select();
        //9.1 为空的时候 把原有的值更改为现有的总数
        if ($every_day_answer_census_res->isEmpty()) {
            $list = EveryDayAnswerCensus::where(['unit_id' => $data['unit_id']])->select();
            $list->update(['unit_number' => $user_total]);
        }
        //9.2 不为空的时候
        foreach ($every_day_answer_census_res as $k => $v) {
            //9.2.1把字符串user_id 转为数组 有可能存在多个
            $user_id_arr = explode(',', $v['user_ids']);
            //9.2.2判断user_id 总数是1个还是多个
            if (count($user_id_arr) > 1) {
                // 9.2.3 如果存在多个！进行用户id 和 用户数组求差集
                $new_user_ids_array = array_diff($user_id_arr, [$data['user_id']]); //求差集
                // 9.2.4 得到差集进行转为字符串
                $new_user_ids = implode(',', $new_user_ids_array); //转为字符串
                //9.2.5 根据id 更新 重新更新当前记录即可
                EveryDayAnswerCensus::update([
                    'id' => $v['id'],
                    'completed_number' => count($new_user_ids_array),
                    'unit_number' => $user_total,
                    'user_ids' => $new_user_ids
                ]);
            } else {
                //9.2.6如果该用户user_id 只为单一，直接删除
                EveryDayAnswerCensus::destroy($v['id']);
            }
        }
        //9.2.7 更新删除以外的数据总数
        EveryDayAnswerCensus::where('unit_id', $data['unit_id'])->update([
            'unit_number' => $user_total,
        ]);
        //新增到日志
        OperateUserLog::create([
            'old_unit_id' => $data['unit_id'],
            'new_unit_id' => $data['unit_id'],
            'type' => OperateUserLog::ONE_TYPE, //移除
            'exercise_user_id' => $this->request->wx_id
        ]);
        //10. 返回结果集
        return $this->response();
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/27 10:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *回收区列表
     */
    public function recoveryPerson()
    {
        $limit = $this->request->param('limit', 12);
        $map = [];
        if ($this->request->has('keyword') && !empty($this->request->param('keyword'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('keyword') . '%'];
        }
        $res = Users::onlyTrashed()->with(['unit'])->where($map)->field('id,username,nickname,head_img,unit_id,is_admin')->paginate($limit)->each(function ($item, $key) {
            $unit_parent_arr = $this->search->getParents($item['unit_id']);
            $unit_parent_str = "";
            foreach ($unit_parent_arr as $key => $value) {
                if ($value['pid'] !== 0) {
                    $unit_parent_str .= $value['unit_title'] . '-';
                }

            }
            $item['unit_parent'] = rtrim($unit_parent_str, '-');
            return $item;
        });
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/27 11:45
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 恢复到当前单位用户信息
     */
    public function recoveryUserEvent()
    {
        $data = $this->request->param();
        $new_unit_id = $data['new_unit_id']; //恢复到的单位网点id
        //1.查询用户
        $user = Users::withTrashed()->field('id,username,nickname,head_img,unit_id,is_admin')->find($data['user_id']);
        //1.1 判断用户是否为空 为空直接返回
        if (is_null($user)) {
            return $this->response(404, '未找到该用户');
        }
        //1.1.1 恢复用户
        $user->restore();
        //1.1.2 更新网点信息
        $user->save(['unit_id' => $new_unit_id]);
        //2.查询恢复前每日答题的表[topic_user_day]  条件为网点id 及用户id
        $topic_user_day_res = TopicUserDay::withTrashed()->where(['unit_id' => $data['unit_id']])->where('user_id', $data['user_id'])->select();
        //2.1判断是否为空
        if (!$topic_user_day_res->isEmpty()) {
            //2.1.1不为空的时候进行循环恢复数据
            foreach ($topic_user_day_res as $key => $v) {
                $topicUserDay = TopicUserDay::withTrashed()->find($v['id']);
                //2.1.2恢复数据
                $topicUserDay->restore();
                // 2.1.3 恢复数据后进行更新为新的网点信息
                $topicUserDay->save(['unit_id' => $new_unit_id]);

            }
        }
        //3.查询每日答题同步表[topic_user_day_sync] 条件为网点id 及用户id
        $topic_user_day_sync_res = TopicUserDaySync::withTrashed()->where(['unit_id' => $data['unit_id']])->where('user_id', $data['user_id'])->select();
        //3.1判断是否为空
        if (!$topic_user_day_sync_res->isEmpty()) {
            //3.1.1不为空的时候进行循环恢复数据
            foreach ($topic_user_day_sync_res as $key1 => $v1) {
                $topic_user_day_sync = TopicUserDaySync::withTrashed()->find($v1['id']);
                //3.1.2恢复数据
                $topic_user_day_sync->restore();
                // 3.1.3恢复数据后进行更新为新的网点信息
                $topic_user_day_sync->save(['unit_id' => $new_unit_id]);

            }
        }
        //4.总人数
        $persons_total = Users::where('unit_id', $new_unit_id)->count();
        //5.答题人数 [3,4] 均为可答题人员
        $user_total = Users::where('unit_id', $new_unit_id)->whereIn('wx_role_id', [3, 4])->count();
        //6.查询单位总数表[unit_total] 条件为网点id
        $unit_total_res_restore = UnitTotal::where(['unit_id' => $new_unit_id])->findOrEmpty();
        //6.1 判断是否为空
        if (!$unit_total_res_restore->isEmpty()) {
            $unit_total_res_restore->save([
                'persons_total' => $persons_total,
                'answer_persons_total' => $user_total,
            ]);
        }
        //7.每日答题统计答题网点是否完成答题表[every_day_answer_census]  whereFindInSet 查询当前user_ids中是否包含该用户 条件为网点id 及用户id
        $every_day_answer_census_res = EveryDayAnswerCensus::withTrashed()->where(['unit_id' => $new_unit_id])->select();
        //7.1 为空的时候 把原有的值更改为现有的总数
        if ($every_day_answer_census_res->isEmpty()) {
            $list = EveryDayAnswerCensus::where(['unit_id' => $new_unit_id])->select();
            if (!$list->isEmpty()) {
                $list->update(['unit_number' => $user_total]);
            }
        } else {
            //7.2 不为空的时候
            foreach ($every_day_answer_census_res as $k => $v2) {
                //7.2.1 查询当前删除信息的数据
                $every_day = EveryDayAnswerCensus::withTrashed()->find($v2['id']);

                //7.2.2 查询当前删除的信息进行恢复
                $every_day->restore();
                //7.2.3 查询当前日期该用户是否答题了 如果答题 进行合并user_ids

                $is_dt = TopicUserDay::where(['date_of' => $v2['date_of'], 'user_id' => $data['user_id']])->findOrEmpty();

                //7.2.3.1 不为空的时候 user_ids 进行拼接更新

                $new_user_ids = "";
                if (!$is_dt->isEmpty()) {
                    $new_user_ids = $data['user_id'];
                }

                //7.2.3.1.1 转为数组
                $is_user_id_arr = explode(',', $every_day['user_ids']);

                //判断数组是否包含 $data['user_id']
                if (!in_array($new_user_ids, $is_user_id_arr)) {
                    //7.2.3.2 新的数组user_ids 字符串
                    $new_user_ids_arr = $every_day['user_ids'] . ',' . $new_user_ids;
                } else {
                    $new_user_ids_arr = $every_day['user_ids'];
                }
                //7.2.4 user_ids 转为数组
                $user_id_arr = explode(',', $new_user_ids_arr);
                //7.2.4.1 更新
                $every_day->save([
                    'completed_number' => count($user_id_arr),
                    'unit_number' => $user_total,
                    'user_ids' => rtrim($new_user_ids_arr, ",") //去除最后一个逗号
                ]);
            }
        }
        //8.1 更新以外的数据总数
        EveryDayAnswerCensus::where('unit_id', $new_unit_id)->update([
            'unit_number' => $user_total,
        ]);
        //新增到日志
        OperateUserLog::create([
            'old_unit_id' => $data['unit_id'],
            'new_unit_id' => $new_unit_id,
            'type' => $this->request->param('type'),
            'exercise_user_id' => $this->request->wx_id
        ]);
        //9. 返回结果集
        return $this->response();
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/27 14:18
     * @return \think\response\Json
     * 添加用户
     */
    public function addUnitUser()
    {
        $data = $this->request->param();
        //1 查询手机号是否存在
        $user = Users::withTrashed()->where(['mobile' => $data['mobile']])->findOrEmpty();
        if (!is_null($user->delete_time)) {
            return $this->response(404, '当前手机号已删除，请在未分配人员中进行恢复');
        }
        if (!$user->isEmpty()) {
            return $this->response(404, '当前手机号存在');
        }
        //2.封装数组
        $data = [
            'username' => $data['nickname'] ?? '',
            'nickname' => $data['nickname'] ?? '',
            'mobile' => $data['mobile'] ?? '',
            'password' => password_hash('111111', PASSWORD_DEFAULT),
            'head_img' => 'https://fakeimg.pl/230x230/18AE66/FFF/?font=noto&text=' . $data['nickname'],
            'unit_id' => $data['unit_id'],
            'industry_id' => 1,
            'create_id' => $data['user_id'],
            'is_admin' => 0,
            'wx_role_id' => 3
        ];
        //3 添加用户入库
        $user_id = Users::create($data)->id;
        //4.查询单位总数表[unit_total] 条件为网点id
        $unit_total_res_restore = UnitTotal::where(['unit_id' => $data['unit_id']])->findOrEmpty();
        //5.总人数
        $persons_total = Users::where('unit_id', $data['unit_id'])->count();
        //6.答题人数 [3,4] 均为可答题人员
        $user_total = Users::where('unit_id', $data['unit_id'])->whereIn('wx_role_id', [3, 4])->count();
        //6.1 判断是否为空 更新单位人员总数表
        if (!$unit_total_res_restore->isEmpty()) {
            $unit_total_res_restore->save([
                'persons_total' => $persons_total,
                'answer_persons_total' => $user_total,
            ]);
        }
        //返回当前用户
        $res = Users::with(['unit'])->findOrEmpty($user_id);
        $unit_parent_arr = $this->search->getParents($data['unit_id']);
        $unit_parent_str = "";
        foreach ($unit_parent_arr as $key => $value) {
            if ($value['pid'] !== 0) {
                $unit_parent_str .= $value['unit_title'] . '-';
            }

        }
        $res['unit_parent'] = rtrim($unit_parent_str, '-');

        //新增到日志
        OperateUserLog::create([
            'old_unit_id' => $data['unit_id'],
            'new_unit_id' => $data['unit_id'],
            'type' => OperateUserLog::TWO_TYPE, //新增
            'exercise_user_id' => $this->request->wx_id
        ]);
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/27 15:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 查询用户所在单位
     */
    public function selectUnitPerson()
    {
        $limit = $this->request->param('limit', 12);
        $map = [];
        if ($this->request->has('keyword') && !empty($this->request->param('keyword'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('keyword') . '%'];
        }
        $map[] = ['is_admin', '=', 0];
        $res = Users::with(['unit'])->where($map)->whereIn('wx_role_id', [3, 4])->field('id,username,nickname,head_img,unit_id,is_admin')->paginate($limit)->each(function ($item, $key) {
            $unit_parent_arr = $this->search->getParents($item['unit_id']);
            $unit_parent_str = "";
            foreach ($unit_parent_arr as $key => $value) {
                if ($value['pid'] !== 0) {
                    $unit_parent_str .= $value['unit_title'] . '-';
                }
            }
            $item['unit_parent'] = rtrim($unit_parent_str, '-');
            return $item;
        });
        return $this->response($res);
    }

    //未答题人员
    public function noAnswerPerson()
    {
        $unit_id = $this->request->param('unit_id', 0);
        $limit = $this->request->param('limit', 12);
        $childUnit = $this->getChildUnit($unit_id, false);
        $date_of = $this->request->param('date_of', date("Y-m-d"));
        $dateWhere[] = array('date_of', '=', $date_of);
        $map = [];
        if ($this->request->has('keyword') && !empty($this->request->param('keyword'))) {
            $map[] = ['username', 'like', '%' . $this->request->param('keyword') . '%'];
        }
        $res = Users::field('id,username,mobile,head_img,unit_id,is_admin')->with(['unit', 'topicDay' => function ($query) use ($dateWhere) {
            $query->where($dateWhere);
            return $query;
        }])->where($childUnit)->where($map)->whereIn('wx_role_id', [3, 4])->paginate($limit)->each(function ($item, $key) {
            $unit_parent_arr = $this->search->getParents($item['unit_id']);
            $unit_parent_str = "";
            foreach ($unit_parent_arr as $key => $value) {
                if ($value['pid'] !== 0) {
                    $unit_parent_str .= $value['unit_title'] . '-';
                }
            }
            $item['unit_parent'] = rtrim($unit_parent_str, '-');
            return $item;
        })->filter(function (Users $users) {
            if (count($users['topicDay']) === 0) {
                return true;
            }
        })->toArray();
        $res['total'] = count(array_values($res['data']));
        $res['data'] = array_values($res['data']);
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/28 11:22
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 下级单位
     */
    public function getXjUnit()
    {
        $unit_id = $this->request->param('unit_id', 1);
//        $childUnit = $this->getChildUnit($unit_id, true);
        $unit = $this->search->getChildren($unit_id, true);
        //$unit = Unit::where($childUnit)->where('level',3)->select()->toArray();
        $new_arr = [];
        foreach ($unit as $key => $value) {
            if ($value['level'] === 3) {
                $new_arr[] = $value;
            }
        }
        return $this->response($new_arr);
    }

    public function aaaa()
    {

//        $abc = \think\facade\Db::connect('video')
//            ->table('amr_videos')
//            ->whereDay('create_time', 'yesterday')
//            ->select()->toArray();
//        foreach ($abc as $key=>$value){
//            $bbc = \think\facade\Db::connect('yz')
//                ->table('amr_videos')
//                ->where('video_id', $value['id'])
//                ->find();
//            if (is_null($bbc)) {
//               $data = [
//                   'sample_id'=>0,
//                   'file_img'=>'',
//                   'file_path'=>$value['file_path'],
//                   'file_name'=>$value['file_name'],
//                   'file_size'=>'',
//                   'file_original'=>$value['file_original'],
//                   'status'=>3,
//                   'whether_status'=>$value['whether_status'],
//                   'suffix'=>$value['suffix'],
//                   'unit'=>'',
//                   'video_type'=>$value['video_type'],
//                   'site_id'=>$value['site_id'],
//                   'quarter'=>'',
//                   'quarter_id'=>$value['quarter'],
//                   'website'=>'http://video.ahamr.cn',
//                   'port'=>'90',
//                   'create_time'=>$value['create_time'],
//                   'update_time'=>$value['update_time'],
//                   'video_id'=>$value['id']
//               ];
//                \think\facade\Db::connect('yz')
//                    ->table('amr_videos')
//                    ->save($data);
//            }
//        }
//        halt("完成");


//
//
//        $date_of = '2022-06-02';
////        $user_id = 2466;
////        $unit_id = 230;
//        $dateWhere[] = array('date_of', '=', '2022-06-16');
//        $user_id = $this->request->param('user_id', 0);
//        $unit_id = $this->request->param('unit_id', 0);
//        $level = $this->request->param('level', 0); //层级
//        if (intval($unit_id) === 0) {
//            $unit_id = 230; //省级id
//        }
////        $unit = Unit::field('id,level')->find($unit_id);
////        if (is_null($unit)) {
////            return $this->response(404, '单位不存在');
////        }
//        //父级单位
//        $parentUnit = $this->getParentUnt($unit_id);
//        //子级单位
//        $childUnit = $this->getChildUnit($unit_id, false);
//        //获取子级网点总数
//        $unit_child_count = $this->UnitCount($unit_id);
//        //1.2查找自己的层级关系
//        $childUnitTitle = $this->tjTitleByLevel($level);
//        if ($level === Unit::LEVEL_THREE) {
//            //获取已答题的网点数 -- 个人
//            $childUnitAnswerNumber = $this->mySelf($unit_id, $dateWhere, $user_id);
//        } else {
//            //获取已答题的网点数 -- 父级
//            $childUnitAnswerNumber = $this->getUnitAnswerNumber($unit_id, $dateWhere);
//        }
//        if (!empty($parentUnit)) {
//            //1.存在父级的时候
//            //1.1 获取父级的单位id
//            $parent_res = $this->getChildUnit($parentUnit[0]['id'], false);
//            //获取父级网点总数
//            $unit_parent_count = $this->UnitCount($parentUnit[0]['id']);
//            //获取父级已答题的网点数
//            $parentUnitAnswerNumber = $this->getUnitAnswerNumber($parentUnit[0]['id'], $dateWhere);
//            //每日统计封装方法
//            $parentResult = $this->dayJs($parent_res, $dateWhere);
//            //获取标题
//            $parentUnitTitle = $this->tjTitleByLevel($parentUnit[0]['level']);
//            $is_parent = true;
//        } else { //不存在父级的时候
//            $parentResult = [];
//            $is_parent = false;
//            $parentUnitTitle = [
//                'title' => '',
//                'table_title' => ''
//            ];
//            $unit_parent_count = 0;
//            $parentUnitAnswerNumber = 0;
//        }
//        if ($unit_child_count > 0) {
//            $mySelfUnitAnswerNumberRate = round(($childUnitAnswerNumber / $unit_child_count) * 100, 2);
//        } else {
//            $mySelfUnitAnswerNumberRate = 0;
//        }
//        if ($unit_parent_count > 0) {
//            $myParentUnitAnswerNumberRate = round(($parentUnitAnswerNumber / $unit_parent_count) * 100, 2);
//        } else {
//            $myParentUnitAnswerNumberRate = 0;
//        }
//
//        //1.1 查找自己的数据
//        $childResult = $this->dayJs($childUnit, $dateWhere);
//        $new_arr = [
//            'result' => [
//                'mySelf' => $childResult,
//                'mySelfTitle' => $childUnitTitle['title'],
//                'mySelfTableTitle' => $childUnitTitle['table_title'],
//                'mySelfUnitCount' => $unit_child_count,
//                'mySelfUnitAnswerNumber' => $childUnitAnswerNumber,
//                'myParentUnitAnswerNumber' => $parentUnitAnswerNumber,
//                'mySelfUnitAnswerNumberRate' => $mySelfUnitAnswerNumberRate, //自己的答题率
//                'myParentUnitAnswerNumberRate' => $myParentUnitAnswerNumberRate,//父级的答题率
//                'myParent' => $parentResult,
//                'myParentTitle' => $parentUnitTitle['title'],
//                'myParentTableTitle' => $parentUnitTitle['table_title'],
//                'myParentUnitCount' => $unit_parent_count,
//            ],
////            'sixteenCity' => $city,
//            'is_parent' => $is_parent,
////            'is_parent_null' => $is_parent_null,
//        ];
//        return $this->response($new_arr);

//        $res = TopicUserDaySync::field('count(*) as zs,date_of')->group('date_of')->select()->toArray();
//        sort($res);
//        halt($res);



//        $unit_id = $this->request->param('unit_id', 16);
////        $childUnit = $this->getChildUnit($unit_id, true);
//        $unit = $this->search->getChildren($unit_id, true);
//        halt($unit);
//        $pinyin = new Pinyin(); // 默认
//        $unit = Unit::select()->toArray();
//        foreach ($unit as $key=>$value){
//            $abc = $pinyin->abbr($value['unit_title'], '-');
//            $abc_arr = explode('-',$abc);
//            $pinyinDx = strtoupper($abc_arr[0]);
//            Unit::update([
//                'id'=>$value['id'],
//                'pinyin'=>$pinyinDx
//            ]);
//        }


////        $res = AuditExam::field('unit_id,attribute')->with(['unit'])->where('attribute','<>',3)->group('unit_id')->select()->toArray();
////        halt($res);
////       return $this->response($res);
//
//
////       $res = AuditExam::field('sum(final_score)')->where('unit_id',16)->where('attribute','<>',3)->where('status','=',2)->select()->toArray();
////       halt($res);
////        halt($res);
//
//        $childUnit = $this->getChildUnit(1, true);
//        $unit = Unit::withCount(['examAudit'])->withCount(['examAudit' => function ($query, &$alias) {
//            $query->where(['status' => 2]); //审核数量
//            $alias = 'points_count';
//            return $query;
//        }])->withCount(['examAudit' => function ($query, &$alias) {
//            $query->where(['status' => 1]); //审核数量
//            $alias = 'no_count';
//            return $query;
//        }])->withAvg(['examAudit' => function ($query, &$alias) {
//            $query->where(['status' => 2]); //审核数量
//            $alias = 'avg_count';
//            return $query;
//        }],'final_score')->withSum(['examAudit' => function ($query, &$alias) {
//            $query->where(['status' => 2]); //审核数量
//            $alias = 'sum_count';
//            return $query;
//        }],'final_score')->where($childUnit)->where('level',3)->select()->each(function ($item,$key){
//            $unit_parent_arr = $this->search->getParents($item['id']);
//            $unit_parent_str = "";
//            foreach ($unit_parent_arr as $key => $value) {
//                if ($value['pid'] !== 0){
//                    $unit_parent_str .= $value['unit_title'] . '-';
//                }
//            }
//            $item['unit_parent'] = rtrim($unit_parent_str, '-');
//            return $item;
//        })->toArray();
//        return $this->response($unit);
        $user = Users::withTrashed()->select();
        foreach ($user as $key=>$value){
            if(strpos($value['head_img'],'https://fakeimg.pl/230x230/18AE66/FFF/?font=noto&text=') !== false){
                Users::withTrashed()->update([
                    'id'=>$value['id'],
                    'head_img'=>NULL
                ]);
            }
//            if($value['head_img'] == null){
//                Users::withTrashed()->update([
//                    'id'=>$value['id'],
//                    'head_img'=>'https://fakeimg.pl/230x230/18AE66/FFF/?font=noto&text='.str_replace(' ','',$value['username'])
//                ]);
//            }
        }
//
//        halt("成功");

    }

}
